<?php

class selectfield extends components {
    
    public function generate($page, $tag) {
        
        # Create the component
        $selectfield = '<select name="'.$this->name.'" class="componentField"/><--componentOptions--></select>';
        
        # Add the component to the defaultcomponent template
        $this->componentPage->append($this->label,'componentLabel');
        $this->componentPage->append($selectfield,'componentComponent');
        
        # Add ids to the component
        $this->componentPage->append($this->name,'componentID');
        $this->componentPage->append($this->name.'Label','componentLabelID');
        $this->componentPage->append($this->name.'Component','componentComponentID');
        
        # If needed add extra cssClasses
        if(isset($this->cssClass)) {
            $this->componentPage->append($this->cssClass,'componentClass');
        }
        
        if(!isset($this->type)) {
            # Prepare the values to be used in the selectfield
            $options = $this->createOptionValues($this->value);
        } else {
            
            switch($this->type){
                case 'getYears':
                    $options = $this->getYears();
                    break;
            }
            
        }
        
        if(isset($options)) {
            $this->componentPage->append($options,'componentOptions');
        }
          
        # Add the component to the form
        $component = $this->componentPage->generateTemplate(true);
        
        $page->append($component,$tag);
        
        parent::generate($page, $tag);
        
    }
    
    private function createOptionValues($values) {
        
        $options = '';
        
        if(isset($this->emptyOption) && $this->emptyOption) {
            $options .= '<option value="-1"></option>';
        }

        if(is_array($values)) {
            foreach($values as $value => $description){
                $options .= '<option value="'.$value.'">'.$description.'</option>';
            }
        } 
        
        return $options;
        
    }
    
    private function getYears() {
        
        if(isset($this->typeSettings)) {
            $startYear = $this->typeSettings['startYear'];
            $endYear = $this->typeSettings['endYear'];
        } else {
            $startYear = date("Y") - 100;
            $endYear = date("Y");
        }
        
        $option = '';
        for($year = $endYear; $year >= $startYear; $year--) {
            $option .= '<option value="'.$year.'">'.$year.'</option>';
        }
        
        return $option;
        
    }
    
}

?>
